<template>
  <div class="advertiser-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>广告商管理</span>
          <el-button type="primary" @click="handleAdd">新增广告商</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="广告商名称">
          <el-input v-model="searchForm.name" placeholder="请输入广告商名称" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 广告商列表 -->
      <el-table :data="filteredAdvertisers" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="广告商名称" />
        <el-table-column prop="website" label="网站链接" width="150" show-overflow-tooltip />
        <el-table-column label="广告图片" width="120">
          <template #default="{ row }">
            <el-image 
              v-if="row.adimage" 
              :src="row.adimage" 
              style="width: 80px; height: 60px; object-fit: cover;"
              :preview-src-list="[row.adimage]"
              fit="cover"
            />
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="广告收入" width="100">
          <template #default="{ row }">
            <span v-if="row.adincome !== undefined">¥{{ row.adincome }}</span>
            <span v-else>¥0</span>
          </template>
        </el-table-column>
        <el-table-column label="投放时间" width="180">
          <template #default="{ row }">
            <span v-if="row.adtime">{{ formatDate(row.adtime) }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" width="200">
          <template #default="{ row }">
            <span v-if="row.remark">{{ row.remark }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增广告商' : '编辑广告商'"
      width="600px"
    >
      <el-form ref="advertiserFormRef" :model="advertiserForm" :rules="formRules" label-width="100px">
        <el-form-item label="广告商名称" prop="name">
          <el-input v-model="advertiserForm.name" placeholder="请输入广告商名称" />
        </el-form-item>
        <el-form-item label="网站链接" prop="website">
          <el-input v-model="advertiserForm.website" placeholder="请输入网站地址" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="advertiserForm.remark" 
            type="textarea" 
            :rows="3"
            placeholder="请输入备注信息" 
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAdsList, 
  createAds , 
  updateAds, 
  deleteAds
} from '@/api/advertiser.js'

// 数据
const loading = ref(false)
const advertisers = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  name: ''
})

// 对话框状态
const dialogVisible = ref(false)
const dialogType = ref('add')

// 广告商表单
const advertiserForm = reactive({
  id: null,
  name: '',
  website: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入广告商名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 模拟数据
const mockAdvertisers = [
  {
    id: 1,
    name: '百度推广',
    website: 'https://e.baidu.com',
    remark: '主要广告合作伙伴，CPC效果良好',
    adimage: 'https://via.placeholder.com/300x200?text=百度推广',
    adincome: 5000,
    adtime: '2024-01-15T10:30:00Z'
  },
  {
    id: 2,
    name: '腾讯广告',
    website: 'https://ad.qq.com',
    remark: '社交媒体广告，覆盖面广',
    adimage: 'https://via.placeholder.com/300x200?text=腾讯广告',
    adincome: 8000,
    adtime: '2024-01-20T14:45:00Z'
  },
  {
    id: 3,
    name: '阿里妈妈',
    website: 'https://www.alimama.com',
    remark: '电商广告，转化率高',
    adimage: 'https://via.placeholder.com/300x200?text=阿里妈妈',
    adincome: 12000,
    adtime: '2024-01-25T09:15:00Z'
  },
  {
    id: 4,
    name: '字节跳动广告',
    contact: '赵经理',
    phone: '13800138004',
    email: 'zhao@bytedance.com',
    website: 'https://www.toutiao.com',
    address: '北京市海淀区北三环西路43号',
    cooperationType: 'cpa',
    remark: '信息流广告，精准投放',
    status: 'active',
    isDefault: false
  },
  {
    id: 5,
    name: '微博广告',
    contact: '陈经理',
    phone: '13800138005',
    email: 'chen@weibo.com',
    website: 'https://weibo.com',
    address: '北京市海淀区东北旺西路8号',
    cooperationType: 'brand',
    remark: '品牌合作，提升知名度',
    status: 'active',
    isDefault: false
  }
]

// 计算属性：过滤后的广告商列表
const filteredAdvertisers = computed(() => {
  let result = advertisers.value

  // 搜索过滤：按公司名称（adcompany）搜索
  if (searchForm.name) {
    result = result.filter(item => 
      item.name.toLowerCase().includes(searchForm.name.toLowerCase())
    )
  }

  // 分页
  total.value = result.length
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return result.slice(start, end)
})

// 方法
// 数据转换函数：将后端数据格式转换为前端格式
const transformBackendData = (backendData) => {
  if (!backendData || !Array.isArray(backendData)) {
    return []
  }
  
  return backendData.map(item => ({
    id: item.adid,
    name: item.adcompany || '未知广告商',
    website: item.adlink || '',
    remark: item.adremarks || '',
    adimage: item.adimage, // 保留图片信息
    adtime: item.adtime, // 保留时间信息
    adincome: item.adincome // 保留收入信息
  }))
}

const getAdvertiserList = async () => {
  loading.value = true
  
  try {
    const response = await getAdsList({
      page: currentPage.value,
      size: pageSize.value,
      name: searchForm.name
    })
    
    if (response.data) {
      console.log('获取广告商列表:', response.data)
      
      // 检查返回的数据格式，如果是后端格式则转换
      let dataList = response.data.list || response.data
      if (Array.isArray(dataList) && dataList.length > 0 && dataList[0].adid) {
        // 这是后端数据格式，需要转换
        advertisers.value = transformBackendData(dataList)
      } else {
        // 这是前端格式或模拟数据
        advertisers.value = dataList
      }
      
      total.value = response.data.total || advertisers.value.length
      ElMessage.success('广告商数据加载成功')
    } else {
      // 如果API返回空数据，使用模拟数据作为回退
      advertisers.value = mockAdvertisers
      total.value = mockAdvertisers.length
      ElMessage.info('当前使用模拟数据')
    }
  } catch (error) {
    console.error('获取广告商列表失败:', error)
    // 如果API调用失败，回退到模拟数据
    advertisers.value = mockAdvertisers
    total.value = mockAdvertisers.length
    ElMessage.error('获取广告商列表失败，使用模拟数据')
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除广告商"${row.name}"吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    try {
      const response = await deleteAds(row.id)
      if (response.success) {
        const index = advertisers.value.findIndex(item => item.id === row.id)
        if (index > -1) {
          advertisers.value.splice(index, 1)
          total.value = advertisers.value.length
          ElMessage.success('删除成功')
        }
      } else {
        ElMessage.error(response.message || '删除失败')
      }
    } catch (error) {
      console.error('删除广告商失败:', error)
      // API调用失败时，使用本地模拟
      const index = advertisers.value.findIndex(item => item.id === row.id)
      if (index > -1) {
        advertisers.value.splice(index, 1)
        total.value = advertisers.value.length
        ElMessage.success('删除成功（模拟）')
      }
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除广告商失败:', error)
      ElMessage.error('删除广告商失败，请稍后重试')
    }
  }
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleReset = () => {
  searchForm.name = ''
  currentPage.value = 1
}

const handleSizeChange = (val) => {
  pageSize.value = val
}

const handleCurrentChange = (val) => {
  currentPage.value = val
}

const handleAdd = () => {
  dialogType.value = 'add'
  Object.assign(advertiserForm, {
    id: null,
    name: '',
    website: '',
    remark: ''
  })
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(advertiserForm, row)
  dialogVisible.value = true
}



const handleSubmit = async () => {
  try {
    if (dialogType.value === 'add') {
      // 新增
      try {
          const response = await createAds(advertiserForm)
        if (response.success) {
          advertisers.value.push(response.data)
          total.value = advertisers.value.length
          ElMessage.success('新增成功')
        } else {
          ElMessage.error(response.message || '新增失败')
        }
      } catch (error) {
        console.error('新增广告商失败:', error)
        // API调用失败时，使用本地模拟
        const newAdvertiser = {
          ...advertiserForm,
          id: Math.max(...advertisers.value.map(item => item.id)) + 1
        }
        advertisers.value.push(newAdvertiser)
        total.value = advertisers.value.length
        ElMessage.success('新增成功（模拟）')
      }
    } else {
      // 编辑
      try {
        const response = await updateAds(advertiserForm.id, advertiserForm)
        if (response.success) {
          const index = advertisers.value.findIndex(item => item.id === advertiserForm.id)
          if (index > -1) {
            advertisers.value[index] = response.data
            ElMessage.success('编辑成功')
          }
        } else {
          ElMessage.error(response.message || '编辑失败')
        }
      } catch (error) {
        console.error('编辑广告商失败:', error)
        // API调用失败时，使用本地模拟
        const index = advertisers.value.findIndex(item => item.id === advertiserForm.id)
        if (index > -1) {
          advertisers.value[index] = { ...advertiserForm }
          ElMessage.success('编辑成功（模拟）')
        }
      }
    }
    dialogVisible.value = false
  } catch (error) {
    console.error('提交表单失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  }
}

// 辅助函数
const formatDate = (dateString) => {
  if (!dateString) return ''
  
  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch (error) {
    console.error('日期格式化失败:', error)
    return dateString
  }
}

// 生命周期
onMounted(() => {
  getAdvertiserList()
})
</script>

<style scoped>
.advertiser-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>